#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>

/*错误码*/
int g_exitStatus = -1;
int main()
{
#if 0
    // 进程号
    pid_t pid = getpid();
    std::cout << "pid" << pid << std::endl;

    // 父进程ID号
    pid_t ppid = getppid();
    std::cout << "ppid" << ppid << std::endl;

    int cnt = 60;
    while (cnt--)
    {
        sleep(1);
    }
#endif

    int val = 100;

    pid_t pid = fork();
    if (pid == -1)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid == 0)
    {
        sleep(3);
        std::cout << "child process id:" << getpid() << std::endl;
        std::cout << "child process" << std::endl;
        std::cout << "child parent prcess id:" << getppid() << std::endl;

        /*退出进程*/

        _exit(g_exitStatus);

        std::cout << "child parent val = " << val << std::endl;

        /*子进程读文件*/
        int fd = open("./record.txt", O_RDONLY);
        read(fd, &val, sizeof(int));

        std::cout << "chiled process val = " << val << std::endl;
        close(fd);
    }
    else
    {
        int childStatus = 0;
        /*下面两种方式是等价的*/
        // wait(&childStatus);
        waitpid(pid, &childStatus, 0);

        std::cout << "childStatus:" << childStatus << std::endl;
        std::cout << "childStatus:" << WEXITSTATUS(childStatus) << std::endl;

        /*阻塞 block.....*/

        std::cout << "parent process ret pid" << pid << std::endl;
        std::cout << "parent process" << std::endl;
        std::cout << "parent process" << getpid() << std::endl;
        std::cout << "parent val = " << val << std::endl;
        val += 10000;
        std::cout << "parent val = " << val << std::endl;

        /*父进程写数据*/
        const char *filename = "./record.txt";
        int fd = open(filename, O_RDWR | O_CREAT, 0644);

        int writeBytes = write(fd, (const void *)&val, sizeof(int));

        /*关闭文件*/
        close(fd);
    }
    std::cout << "hello world" << std::endl;

    sleep(1);
    int cnt = 100;
    while (cnt--)
    {
        sleep(1);
    }

    return 0;
}